package com.kpmg.datalake.common.service.impl;

import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.kpmg.datalake.common.constants.Constants;
import com.kpmg.datalake.common.enums.ResultCodeEnum;
import com.kpmg.datalake.common.enums.SystemParamsEnum;
import com.kpmg.datalake.common.exception.BusinessException;
import com.kpmg.datalake.common.service.IComSystemParamsService;
import com.kpmg.datalake.common.service.IDataLakeDataService;
import com.kpmg.datalake.common.utils.AssertUtil;
import com.kpmg.datalake.common.utils.EncrypUtil;
import com.kpmg.datalake.db.model.Project;
import com.kpmg.datalake.schedule.utils.ftp.SftpClient;
import java.io.File;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-08-23 22:19:53 dataLake 项目数据同步
 */
@Service
public class DataLakeDataServiceImpl implements IDataLakeDataService {


  @Resource
  private IComSystemParamsService comSystemParamsService;

  /**
   * 项目数据文件下载
   *
   * @param project 项目信息
   * @return List
   */
  @Override
  public List<String> fileDownLoad(Project project) throws JSchException, SftpException {
    String localFilePath = this.getFileStorePath(project.getPrjId());
    SftpClient sftpClient = null;
    List<String> localFileList = null;
    try {
      //文件完成标示
      boolean fileComplete = false;
      sftpClient = SftpClient
          .connect(project.getSftpIp(), project.getSftpPort(), project.getSftpUser(),
              EncrypUtil.decryptAes(project.getSftpPwd(), Constants.ENCRY_KEY), 0, -1);
      ChannelSftp channel = sftpClient.getChannel();
      String remoteFilePath =
          project.getSftpPath() + SftpClient.LINUX_SEPARATOR + project.getPrjId();
      List<?> fileList = channel.ls(remoteFilePath);
      if (fileList == null) {
        throw new BusinessException(ResultCodeEnum.CODE4023,
            String.format("%s 文件路径不存在", remoteFilePath));
      } else {
        if (CollectionUtils.isEmpty(fileList)) {
          throw new BusinessException(ResultCodeEnum.CODE4023,
              String.format("%s 文件路径不存在", remoteFilePath));
        }
        for (Object jiaC : fileList) {
          ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) jiaC;
          if ("OK".equals(entry.getFilename())) {
            fileComplete = true;
            break;
          }
        }
      }
      //是否完成
      if (fileComplete) {
        localFileList = sftpClient.batchDownLoadFile(remoteFilePath, localFilePath, false);
      }
    } finally {
      if (sftpClient != null) {
        sftpClient.disconnect();
      }
    }

    return localFileList;
  }


  /**
   * 获取sftp 文件存放路径
   *
   * @return String
   */
  private String getFileStorePath(String projectId) {
    String fileStorePath;
    try {
      String dataLakeDataFileStore = comSystemParamsService
          .getSystemParamsByCode(SystemParamsEnum.DATA_LAKE_DATAFILE_STORE.getCode());
      AssertUtil.assertNotEmpty(dataLakeDataFileStore, "本地路径未配置");
      fileStorePath = dataLakeDataFileStore + File.separator + projectId;
      File file = new File(fileStorePath);
      //判断文件路径是否存在
      if (!file.exists() && !file.mkdirs()) {
        throw new BusinessException(ResultCodeEnum.CODE9999,
            String.format("创建文件 %s", fileStorePath));
      }
    } catch (BusinessException e) {
      fileStorePath = System.getProperty("user.home") + File.separator + projectId;
      File fileLocalUser = new File(fileStorePath);
      if (!fileLocalUser.mkdirs()) {
        throw new BusinessException(ResultCodeEnum.CODE9999, "获取本地文件存储路径异常");
      }
    }
    return fileStorePath;
  }

}
